package com.xiaobai.config;

import com.xiaobai.exception.InterceptorException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(request.getRequestURI().contains("moon")) {
            return true;//更新MOON 通过
        }
        if("/course/updateWeekCourse".equals(request.getRequestURI()) ||
                "/course/resetWeekCourse".equals(request.getRequestURI())){
            return true;//重置周课表和更新当前周的课程 通过
        }
        String studentId=request.getHeader("studentId");
        // 游客专用通道
        if("111111".equals(studentId)){
            MyStudentIdManager.set(studentId);
            // 首次数据 || 上报接口
            return request.getRequestURI().equals("/user/wxFirstLogin") || request.getRequestURI().startsWith("/health-report");
            //游客的其他业务不给通过(因为不能连接官网)
        }

        String openid=request.getHeader("openid");
        String uuid=request.getHeader("uuid");

        if(StringUtils.isBlank(studentId)){
            log.error("ip:" + getRemoteAddr(request));
            throw new InterceptorException("用户不存在!");
        }

        //然后去redis中查询验证身份
        String redisValue=stringRedisTemplate.opsForValue().get("security:"+studentId);

        uuid = openid + "@" + uuid;

        if (StringUtils.isBlank(redisValue)) {
            // 可以通过, KEY过期了, 这里更新一下
            stringRedisTemplate.opsForValue().set("security:"+studentId, uuid);
            // 会走到return true
        }else if(!StringUtils.equals(redisValue,uuid)){
            log.error("ip:" + getRemoteAddr(request));
            log.info("学号:{},redisValue:{},uuid:{}",studentId,redisValue,uuid);
            throw new InterceptorException("身份信息错误");
        }

        MyStudentIdManager.set(studentId);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MyJSESSIONIdManager.remove();
        MyStudentIdManager.remove();
    }

    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
